// packageUser/pages/revise-password/index.js
import Notify from "@vant/weapp/notify/notify";
import Toast from "@vant/weapp/toast/toast";
import {verifyInput} from  "../../../utils/Util";
import User from "../../../service/User";
import Notification from "../../../utils/Notification"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        loading: false,
        formData: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /*
    * input数据接收
    * */
    onInputChange: function (e) {
        let name = e.currentTarget.dataset.name;
        let val = e.detail.type || e.detail;
        this.setData({["formData." + name]: val});
    },

    /*
    * 提交
    * */
    onSubmit: async function () {
        try {
            const that = this;
            let password = this.data.formData.password;
            let passwordConfirm = this.data.formData.passwordConfirm;
            let loading = this.data.loading;
            if (!verifyInput(password)) {
                Notify({type: "warning", message: "请输入修改密码"});
                return false
            } else if (!verifyInput(passwordConfirm)) {
                Notify({type: "warning", message: "请输入确认修改密码"});
                return false
            } else if (password !== passwordConfirm) {
                Notify({type: "warning", message: "确认密码不正确"});
                return false
            } else if (loading) {
                return false
            } else {
                this.setData({loading: true});
                await User.revisePassword({
                    password: passwordConfirm
                })
                setTimeout(function () {
                    Notification.post({
                        name: "revisePassword",
                        info: {login: true}
                    })
                    wx.navigateBack();
                }, 1500)
                Toast.success({
                    mask: true,
                    duration: 1500, // 持续展示 toast
                    message: "修改成功"
                });
            }
        } catch (e) {
            Toast.loading({
                mask: true,
                duration: 3000, // 持续展示 toast
                message: e.errMsg || "修改密码失败",
                selector: "#van-toast"
            });
            console.error(e)
        } finally {
            this.setData({loading: false});
        }

    }
})